package cn.wen.bases.framework.ibatis.engine.type;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.SQLException;

import org.apache.log4j.Logger;

import cn.wen.java.utils.Converter;

import com.ibatis.sqlmap.client.extensions.ParameterSetter;
import com.ibatis.sqlmap.client.extensions.ResultGetter;
import com.ibatis.sqlmap.client.extensions.TypeHandlerCallback;

public class BlobTypeHandler implements TypeHandlerCallback {

    private Logger log = Logger.getLogger(getClass());

    @Override
    public Object getResult(ResultGetter getter) throws SQLException {
	if (getter.wasNull()) return null;

	return getter.getBlob().getBytes(1L, (int) getter.getBlob().length());
    }

    @Override
    public void setParameter(ParameterSetter setter, Object param) throws SQLException {
	if (!(param instanceof File || param instanceof Blob || param instanceof byte[])) {
	    throw new IllegalArgumentException("参数类型不合法，目前支持的javaType : java.io.File，java.sql.Blob，byte[]");
	}

	if (param instanceof File) {
	    File file = (File) param;
	    InputStream is = null;
	    try {
		is = new BufferedInputStream(new FileInputStream(file));
	    }
	    catch (FileNotFoundException e) {
		log.error(e.getMessage(), e);
		throw new SQLException(e.getMessage());
	    }
	    setter.setBinaryStream(is, Converter.convert(file.length(), Integer.class));
	    return;
	}

	if (param instanceof Blob) {
	    Blob blob = (Blob) param;
	    setter.setBlob(blob);
	    return;
	}

	if (param instanceof byte[]) {
	    byte[] bytes = (byte[]) (byte[]) param;
	    InputStream is = new ByteArrayInputStream(bytes);
	    setter.setBinaryStream(is, bytes.length);
	    return;
	}
    }

    @Override
    public Object valueOf(String s) {
	// TODO Auto-generated method stub
	return s;
    }

}
